package org.sample.io.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Handler {

    private int buffSize = 1024;

    private Charset localCharset = StandardCharsets.UTF_8;

    public Handler() {
    }

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
        sc.configureBlocking(false);
        sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(buffSize));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer buffer = (ByteBuffer) key.attachment();
        buffer.clear();

        if (sc.read(buffer) == -1) {
            sc.close();
        } else {
            buffer.flip();
            String receivedStr = localCharset.newDecoder().decode(buffer).toString();
            System.out.println(receivedStr);

            StringBuilder sendString = new StringBuilder();
            sendString.append("HTTP/1.1 200 OK\r\n");//响应报文首行，200表示处理成功
            sendString.append("Content-Type:text/html;charset=" + localCharset + "\r\n");
            sendString.append("\r\n");// 报文头结束后加一个空行

            sendString.append("<html><head><title>显示报文</title></head><body>");
            sendString.append("接收到请求报文是：<br/>");
            sendString.append(receivedStr + "<br/>");
            sendString.append("</body></html>");

            buffer = ByteBuffer.wrap(sendString.toString().getBytes(localCharset));
            sc.write(buffer);
            sc.close();
        }
    }
}
